package net.starwifi.duobao.web;

import net.starwifi.duobao.FileInfo;
import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.entity.Product;
import net.starwifi.duobao.entity.ProductImage;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.mvc.PageView;
import net.starwifi.duobao.service.FileService;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.service.ProductImageService;
import net.starwifi.duobao.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2015/11/10.
 */
@Controller("productController")
@RequestMapping("/bCenter/product")
public class ProductController extends BaseController {

    @Autowired
    FileService fileService;

    @Autowired
    ProductService productService;

    @Autowired
    ProductImageService productImageService;

    @Autowired
    MemberService memberService;

    /**
     * 信息填写页面
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(PageView pageView, ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        pageView.addOrder(Order.desc("id"));
        model.addAttribute("page", productService.getScrollData(pageView));
        return "bcenter/product-list";
    }


    /**
     * 信息填写页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public  String productAdd(HttpServletRequest request) {
        return "bcenter/product-add";
    }


    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Product product,  HttpServletRequest request, RedirectAttributes redirectAttributes) {
        for (Iterator<ProductImage> iterator = product.getProductImages().iterator(); iterator.hasNext();) {
            ProductImage productImage = iterator.next();
            if (productImage == null || productImage.isEmpty()) {
                iterator.remove();
                continue;
            }
            if (productImage.getFile() != null && !productImage.getFile().isEmpty()) {
                if (!fileService.isValid(FileInfo.FileType.image, productImage.getFile())) {
                    addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid"));
                    return "redirect:add";
                }
            }
        }
        if (!isValid(product)) {
            return ERROR_VIEW;
        }
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
        product.setSn(format.format(new Date()));
        product.setAllocatedStock(0);
        product.setScore(0F);
        product.setTotalScore(0L);
        product.setScoreCount(0L);
        product.setHits(0L);
        product.setWeekHits(0L);
        product.setMonthHits(0L);
        product.setSales(0L);
        product.setWeekSales(0L);
        product.setMonthSales(0L);
        product.setWeekHitsDate(new Date());
        product.setMonthHitsDate(new Date());
        product.setWeekSalesDate(new Date());
        product.setMonthSalesDate(new Date());
        product.setReviews(null);
        product.setConsultations(null);
        product.setIsGift(Boolean.FALSE);
        Member member=memberService.getCurrent();
        product.setShopId(member.getId());
        product.setShopName(member.getShopName());
        for (ProductImage productImage : product.getProductImages()) {
            productImageService.build(productImage,"/product/"+product.getSn()+"/");
        }
        Collections.sort(product.getProductImages());
        if (product.getImage() == null && product.getThumbnail() != null) {
            product.setImage(product.getThumbnail());
        }
        productService.save(product);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list";
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        model.addAttribute("entity", productService.find(id));
        return "bcenter/product-edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Product product, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        for (Iterator<ProductImage> iterator = product.getProductImages().iterator(); iterator.hasNext();) {
            ProductImage productImage = iterator.next();
            if (productImage == null || productImage.isEmpty()) {
                iterator.remove();
                continue;
            }
            if (productImage.getFile() != null && !productImage.getFile().isEmpty()) {
                if (!fileService.isValid(FileInfo.FileType.image, productImage.getFile())) {
                    addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid"));
                    return "redirect:edit?id=" + product.getId();
                }
            }
        }
        if (!isValid(product)) {
            return ERROR_VIEW;
        }
        Product pProduct = productService.find(product.getId());
        if (pProduct == null) {
            return ERROR_VIEW;
        }
        for (ProductImage productImage : product.getProductImages()) {
            productImageService.build(productImage,"/product/"+product.getSn()+"/");
        }
        Collections.sort(product.getProductImages());
        if (product.getImage() == null && product.getThumbnail() != null) {
            product.setImage(product.getThumbnail());
        }
        Member member=memberService.getCurrent();
        product.setShopId(member.getId());
        product.setShopName(member.getShopName());
        productService.updateEntity(product,product.getId());
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list";
    }

}
